
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

/**
 * Gui portion of the program
 * Uses DrawFace.java, DrawGnomon.java, SundialMath.java
 * @author Arun Lee, Michael Terada, Marek Lopez
 */
public class ics314ui extends javax.swing.JApplet {

    private double lat;
    private double lon;
    DrawGnomon drawG;
    DrawFace drawF;

    /**
     * Initializes the applet Ics314ui
     */
    @Override
    public void init() {
        /* Set the Nimbus look and feel */
        // <editor-fold defaultstate="collapsed"
        // desc=" Look and feel setting code (optional) ">
		/*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase
         * /tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
                    .getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ics314ui.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ics314ui.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ics314ui.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ics314ui.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        }
        // </editor-fold>

        /* Create and display the applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                    clear();
                    printButton.setEnabled(false);
                    jButton1.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            // call calculate to do calculation
                            validate();
                        }
                    });

                    // Clears and sets field to blank.
                    clearButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            clear();
                        }
                    });

                    printButton.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            // call calculate to do calculation
                            print();
                        }
                    });
                }
            });
        } catch (Exception ex) {
            // ex.printStackTrace();
        }
    }

    /**
     * Having a main enables the resize of the applet with netbeans. Unsure if
     * there is another workaround.
     *
     * @param args
     */
    public static void main(String[] args) {
        new ics314ui().start();
    }

    /**
     * This method is called from within the init() method to initialize the
     * form. WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed"
    // <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {
		java.awt.GridBagConstraints gridBagConstraints;

		jScrollPane1 = new javax.swing.JScrollPane();
		jTextArea1 = new javax.swing.JTextArea();
		jPanel2 = new javax.swing.JPanel();
		jButton1 = new javax.swing.JButton();
		printButton = new javax.swing.JButton();
		clearButton = new javax.swing.JButton();
		jLatitudeField = new javax.swing.JTextField();
		jLongitudeField = new javax.swing.JTextField();
		jDateField = new javax.swing.JTextField();
		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();

		setBackground(new java.awt.Color(204, 204, 204));
		getContentPane().setLayout(new java.awt.GridBagLayout());

		jScrollPane1.setBackground(java.awt.Color.lightGray);
		jScrollPane1.setBorder(null);

		jTextArea1.setColumns(20);
		jTextArea1.setLineWrap(true);
		jTextArea1.setRows(5);
		jTextArea1.setWrapStyleWord(true);
		jScrollPane1.setViewportView(jTextArea1);

		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 10;
		gridBagConstraints.gridwidth = 4;
		gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
		gridBagConstraints.ipadx = 832;
		gridBagConstraints.ipady = 460;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.weightx = 1.0;
		gridBagConstraints.weighty = 1.0;
		gridBagConstraints.insets = new java.awt.Insets(15, 10, 11, 10);
		getContentPane().add(jScrollPane1, gridBagConstraints);

		org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(
				jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(
				org.jdesktop.layout.GroupLayout.LEADING).add(0, 0,
				Short.MAX_VALUE));
		jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(
				org.jdesktop.layout.GroupLayout.LEADING).add(0, 0,
				Short.MAX_VALUE));

		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 0;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		getContentPane().add(jPanel2, gridBagConstraints);

		jButton1.setText("Create Gnomon");
		jButton1.setMaximumSize(new java.awt.Dimension(150, 30));
		jButton1.setMinimumSize(new java.awt.Dimension(150, 30));
		jButton1.setPreferredSize(new java.awt.Dimension(100, 30));
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 3;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.gridheight = 3;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(14, 18, 0, 0);
		getContentPane().add(jButton1, gridBagConstraints);

		printButton.setText("Print");
		printButton.setMaximumSize(new java.awt.Dimension(150, 30));
		printButton.setMinimumSize(new java.awt.Dimension(150, 30));
		printButton.setPreferredSize(new java.awt.Dimension(100, 30));
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 3;
		gridBagConstraints.gridy = 4;
		gridBagConstraints.gridheight = 3;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(6, 18, 0, 0);
		getContentPane().add(printButton, gridBagConstraints);

		clearButton.setText("Clear All");
		clearButton.setMaximumSize(new java.awt.Dimension(150, 30));
		clearButton.setMinimumSize(new java.awt.Dimension(150, 30));
		clearButton.setPreferredSize(new java.awt.Dimension(100, 30));
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 3;
		gridBagConstraints.gridy = 7;
		gridBagConstraints.gridheight = 3;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(6, 18, 0, 0);
		getContentPane().add(clearButton, gridBagConstraints);

		jLatitudeField.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jLatitudeFieldActionPerformed(evt);
			}
		});
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 2;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.gridheight = 2;
		gridBagConstraints.ipadx = 243;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(16, 10, 0, 0);
		getContentPane().add(jLatitudeField, gridBagConstraints);

		jLongitudeField.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jLongitudeFieldActionPerformed(evt);
			}
		});
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 2;
		gridBagConstraints.gridy = 4;
		gridBagConstraints.gridheight = 2;
		gridBagConstraints.ipadx = 243;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(7, 10, 0, 0);
		getContentPane().add(jLongitudeField, gridBagConstraints);
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 2;
		gridBagConstraints.gridy = 7;
		gridBagConstraints.gridheight = 2;
		gridBagConstraints.ipadx = 243;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(3, 10, 0, 0);
		getContentPane().add(jDateField, gridBagConstraints);

		jLabel1.setText("Latitude");
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 1;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(19, 18, 0, 0);
		getContentPane().add(jLabel1, gridBagConstraints);

		jLabel2.setText("Longitude");
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 4;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0);
		getContentPane().add(jLabel2, gridBagConstraints);

		jLabel3.setText("Date");
		gridBagConstraints = new java.awt.GridBagConstraints();
		gridBagConstraints.gridx = 1;
		gridBagConstraints.gridy = 7;
		gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
		gridBagConstraints.insets = new java.awt.Insets(6, 34, 0, 0);
		getContentPane().add(jLabel3, gridBagConstraints);
	}// </editor-fold>//GEN-END:initComponents

    private void jLongitudeFieldActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jLongitudeFieldActionPerformed
        // TODO add your handling code here:
    }// GEN-LAST:event_jLongitudeFieldActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
    }// GEN-LAST:event_jButton1ActionPerformed

    private void jLatitudeFieldActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jLatitudeFieldActionPerformed
        // TODO add your handling code here:
    }// GEN-LAST:event_jLatitudeFieldActionPerformed
		// Variables declaration - do not modify//GEN-BEGIN:variables

	private javax.swing.JButton clearButton;
	private javax.swing.JButton jButton1;
	private javax.swing.JTextField jDateField;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JTextField jLatitudeField;
	private javax.swing.JTextField jLongitudeField;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JTextArea jTextArea1;
	private javax.swing.JButton printButton;

	// End of variables declaration//GEN-END:variables
    /**
     * Creates the gnomon and face with the sundial math class, then sending
     * results to drawface and draw gnomon
     *
     * @param latitude
     * @param longitude
     * @param date
     */
    public void calculate(double latitude, double longitude, String date) {
        // create a SundialMath
        SundialMath test = new SundialMath();
        test.setInputs(latitude, longitude, date); // send the data to
        // SundialMath
        double[] HL = test.getHourLines(); // upload the hour line's degree to
        // HL
        // jTextArea1.append("Type string here"); //This is how to output stuff
        // to the window
        drawG = new DrawGnomon(test.getGnomon());
        drawF = new DrawFace(HL, Double.parseDouble(jLatitudeField.getText()),
                drawG.getLength());
    }

    /**
     * Input validation for latitude and longitude
     */
    public boolean fieldValidation() {
        boolean valid = true;
        if (jLatitudeField == null || jLongitudeField == null
                || jDateField == null) {
            return false;
        }
        try {
            double a = Double.parseDouble(jLatitudeField.getText());
            if (a > 90 || a < -90) {
                jTextArea1.append("\nNumbers must be between -90 to 90\n");
                return false;
            }
        } catch (Exception e) {
            jTextArea1.append("\nPlease enter a number between -90 to 90\n");
            return false;
        }
        try {
            double b = Double.parseDouble(jLongitudeField.getText());
            if (b > 180 || b < -180) {
                jTextArea1.append("\nNumbers must be between -180 to 180\n");
                return false;
            }
        } catch (Exception e) {
            jTextArea1.append("\nPlease enter a number between -180 to 180\n");
            return false;
        }
        return valid;
    }

    /**
     * Checks if input is valid. If true, sets lat and lon.
     */
    public void validate() {
        if (fieldValidation()) {
            lat = Double.parseDouble(jLatitudeField.getText());
            lon = Double.parseDouble(jLongitudeField.getText());
            calculate(lat, lon, jDateField.getText());
            printButton.setEnabled(true);
        }
    }

    public void testValidate() {
        if (fieldValidation()) {
            lat = Double.parseDouble(jLatitudeField.getText());
            lon = Double.parseDouble(jLongitudeField.getText());
            printButton.setEnabled(true);
        }
    }

    /**
     * @return latitude, primarily for test cases
     */
    public double getLatitude() {
        return this.lat;
    }

    /**
     * @return longitude, primarily for test cases
     */
    public double getLongitude() {
        return this.lon;
    }

    /**
     * Used for test purposes. Sets values.
     */
    public void setTestValues(double tempLat, double tempLong, String tempDate) {
        jLatitudeField.setText("" + tempLat);
        jLongitudeField.setText("" + tempLong);
        jDateField.setText(tempDate);
    }

    /**
     * Prints the results of drawFace and drawGnomon
     */
    public void print() {
        PrinterJob job = PrinterJob.getPrinterJob();
        PageFormat pf = job.defaultPage();
        pf.setOrientation(PageFormat.LANDSCAPE);
        job.setPrintable(drawF, pf);

        boolean ok = job.printDialog();
        if (ok) {
            try {
                job.print();
            } catch (PrinterException ex) {
                /* The job did not successfully complete */
            }
        }
        job.setPrintable(drawG, pf);
        ok = job.printDialog();
        if (ok) {
            try {
                job.print();
            } catch (PrinterException ex) {
                /* The job did not successfully complete */
            }
        }
    }

    /**
     * Clears fields and any data that has been input.
     */
    public void clear() {
        lat = 0;
        lon = 0;
        drawF = null;
        drawG = null;
        jLatitudeField.setText("");
        jLongitudeField.setText("");
        jDateField.setText("");
        jTextArea1
                .setText("Instructions:\n"
                + "You can find your latitude and longitude using the site 'http://askgeo.com'\n"
                + "Valid values for latitude are between -90 and 90.\n"
                + "Valid values for longitude are between -180 and 180.\n"
                + "For the date please enter in this format YYYY/MM/DD;\n"
                + "\n"
                + "To use:\n"
                + "Cut the entire piece marked A out, making sure to not cut any black lines.\n"
                + "A correct piece should be a triangle with an attached rectangle.\n"
                + "Fold along the line between the rectangle and triangle, then place fold on the line that makes a 90 degree angle with the base.\n"
                + "Point the 12 towards north if above the equator (if your latitude is positive) and point the 12 south below the equator (if your latitude is negative).\n"
                + "The small end of the gnomon must face the base."
                + "The location of the shadow is the current time.");
        printButton.setEnabled(false);
    }
}
